package cs342.group1.messenger;

import com.example.grouponemessenger.R;
import com.example.grouponemessenger.R.layout;
import com.example.grouponemessenger.R.menu;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class NewConversation extends Activity {

	private Database db; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_conversation);
		db = new Database(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_new_conversation, menu);
		return true;
	}
	
	public void SendMessage(View v){
		EditText usernameText = (EditText)findViewById(R.id.usernameText);
		EditText messageText = (EditText)findViewById(R.id.messageText);
		SendNewMessage task = new SendNewMessage();
		task.execute(usernameText.getText().toString(), messageText.getText().toString());
		EditText errorText = (EditText)findViewById(R.id.NewConversationError);
		int ToCloudId = -1;
		try {
			ToCloudId = task.get();
		}
		catch (Exception e) {
			ToCloudId = -1;
		}
		if(ToCloudId > 0){
			//go to view this persons conversation page
			errorText.setText("Success");
			Intent conversationIntent = new Intent(NewConversation.this,Conversation.class);
			conversationIntent.putExtra("userId",ToCloudId);
	    	startActivity(conversationIntent);
		}
		else{
			//error message here
			errorText.setText("There is no user with that username.");
		}
	}

	
	
	public class SendNewMessage extends AsyncTask<String, Void, Integer> {
		@Override
		protected Integer doInBackground(String... params) {
			db.open();
			int userId = db.CheckUserLoggedIn().CloudId;
			return (new CloudHelper().SendNewMessage(userId, params[0], params[1]));
		}
	}
}
